package gui;

import business.CalendarManager;
import entity.Calendar;
import entity.Event;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;

@Named(value = "calendarBean")
@RequestScoped
public class CalendarBean {

    private String username;
    private Calendar calendar;

    @EJB
    private CalendarManager calendarManager;

    public CalendarBean() {
    }

    public void loadCalendar() {
        if (username != null && !username.equals("")) {
            calendar = calendarManager.findByUser(username).get(0);
        }
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Calendar getCalendar() {
        if (calendar == null) {
            calendar = new Calendar();
        }
        return calendar;
    }

    public void setCalendar(Calendar calendar) {
        this.calendar = calendar;
    }

    public List<Event> getUpcomingEvents() {
        List<Event> upcomingEvents = new ArrayList<>();
        Date now = new Date();
        for (Event event : calendar.getEvents()) {
            if (now.before(event.getDate())) {
                upcomingEvents.add(event);
            }
        }
        Collections.sort(upcomingEvents, (Event event1, Event event2) -> {
            return event1.getDate().compareTo(event2.getDate());
        });
        return upcomingEvents;
    }
}
